package com.demo.controller;


import com.baidu.speech.restapi.asrdemo.AsrMain;
import com.baidu.speech.restapi.common.DemoException;
import com.demo.common.Result;
import com.demo.util.TransLateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("file")
public class FileController {

    //    文件上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Result fileUpload(@RequestParam("type")Integer language, MultipartFile file) throws Exception {
        ApplicationHome h = new ApplicationHome(getClass());
        System.out.println(file.getOriginalFilename());
        File jarF = h.getSource();
        System.out.println(jarF.getParentFile().toString());
        File dir=new File(jarF.getParentFile().toString()+File.separator+"upload");
//        if(!dir.exists()){
//            try {
//                dir.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
        InputStream inputStream=null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long timestamp = System.currentTimeMillis();
        String[] split = file.getOriginalFilename().split("\\.");
        String type=split[split.length-1];
        String name=file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf(type)-1);
//        name=name.replaceAll(" ","");
        System.out.println("name:  "+name+"  type:  "+type);
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+"."+type;
        String wavPath=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+"1.wav";
        String finalPath=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+"2.wav";

        System.out.println(path);
        File destFile=new File(path);
        try {
            FileUtils.copyInputStreamToFile(inputStream,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        File temp=new File("");
//        System.out.println("path===="+temp.getAbsolutePath());
//        String ffmpegPath = temp.getAbsolutePath()+File.separator+"ffmpeg-5.0-essentials_build\\bin\\";
        String ffmpegPath = jarF.getParentFile().toString()+File.separator+"ffmpeg-5.0-essentials_build\\bin\\ffmpeg.exe";
        System.out.println("ffmpegPath:  "+ffmpegPath);
        String covertCommand=ffmpegPath+" -i \""+path+"\" \""+wavPath+"\"";
        BufferedReader bufferedReader =null;
        String line;


        Process covert=Runtime.getRuntime().exec(covertCommand);
        System.out.println("covertCommand ==="+covertCommand);
        bufferedReader = new BufferedReader(new InputStreamReader(covert.getInputStream()));
        while ((line=bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        String command=ffmpegPath+" -i \""+wavPath+"\" -ac 1 -ar 16000 \""+finalPath+"\"";


        System.out.println("=====formatCommand===== "+command);
        Process format=Runtime.getRuntime().exec(command);
        bufferedReader=new BufferedReader(new InputStreamReader(format.getInputStream()));
        while ((line=bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        AsrMain demo = new AsrMain();
        String result = demo.run(finalPath,language);
//        TransLateUtil.getToken();
//        String result=TransLateUtil.method1(language);

        Double size=file.getSize()*1.0/1024/1024;
        BigDecimal b   =   new   BigDecimal(size);
        size=b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
        Map param=new HashMap();
        param.put("name",name);
        param.put("type",type);
        param.put("size",size+"M");
        param.put("realName",timestamp);
//        定位到upload文件夹
        String upload=jarF.getParentFile().toString()+File.separator+"upload";
        System.out.println("返回结果： "+result);

        //        清空文件夹
        deleteFile(new File(upload));
        return Result.ok().msg(result).Data(param);
    }


    private void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    this.deleteFile(f);
                }
            }
            file.delete();
        } else {
            System.out.println("所删除的" + file.getAbsolutePath() + "不存在！");
        }
    }
//    @GetMapping("/download")
//    public String downloadFile(@RequestParam("id")String id, HttpServletResponse response) {
//        ApplicationHome h = new ApplicationHome(getClass());
//        File jarF = h.getSource();
//
//        Map fileMap=service.getFileById(id);
//        if(fileMap==null){
//            return "文件不存在";
//        }
////      真实存在服务器upload文件夹的名称
//        String realName=fileMap.get("realName").toString();
////        文件原始名称
//        String name=fileMap.get("name").toString();
//        String type=fileMap.get("type").toString();
//        if (realName != null) {
//            //设置文件路径
//            String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+realName+"."+type;
//            File file = new File(path);
//            //File file = new File(realPath , fileName);
//            if (file.exists()) {
//                response.setContentType("application/force-download");// 设置强制下载不打开
//                response.setCharacterEncoding("utf-8");
//                try {
//                    name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                response.addHeader("Content-Disposition", "attachment;fileName*=utf-8''" + name+"."+type);// 设置文件名
//                byte[] buffer = new byte[1024];
//                FileInputStream fis = null;
//                BufferedInputStream bis = null;
//                try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
//                    OutputStream os = response.getOutputStream();
//                    int i = bis.read(buffer);
//                    while (i != -1) {
//                        os.write(buffer, 0, i);
//                        i = bis.read(buffer);
//                    }
//                    return "下载成功";
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally { // 做关闭操作
//                    if (bis != null) {
//                        try {
//                            bis.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (fis != null) {
//                        try {
//                            fis.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }
//        return "下载失败";
//    }

}
